package com.chenc.unitdemo.jwt.golbal;

/**
 * @Author: dyhu
 * @Date: 2019/10/22 15:11
 */

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

/**
 * 输出结果的封装，所有restful返回结果类型
 * @param
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Result<T> implements Serializable {
    /**
     * 返回编码
     **/
    private int code = 200;
    /**
     * 提示信息
     */
    private String msg = "success";
    /**
     * 返回的数据
     */
    private T data;


    public Result(T data) {
        this();

        if ("CodeMsg".equals(data.getClass().getSimpleName())) {
            CodeMsg codeMsg = (CodeMsg) data;
            this.code = codeMsg.getCode();
            this.msg = codeMsg.getMsg();
        } else {
            this.data = data;
        }
    }

    /**
     * 成功时
     *
     * @param <T>
     * @return
     */
    public static <T> Result<T> success(T data) {
        return new Result<>(data);
    }

    public static Result success() {
        return new Result();
    }

    /**
     * 查询无结果
     *
     * @return
     */
    public static Result nothing() {
        return new Result<>(CodeMsg.NO_CONTENT);
    }

    /**
     * 参数缺失
     * @return
     */
    public static Result badrequest() {
        return new Result<>(CodeMsg.MISSING_ARGS);
    }

    /**
     * 执行失败返回
     *
     * @return
     */
    public static Result fail() {
        return Result.fail(500, "服务器端异常错误");
    }

    /**
     * 执行失败返回自定义错误
     *
     * @param code
     * @param msg
     * @return
     */
    public static Result fail(int code, String msg) {
        CodeMsg codeMsg = new CodeMsg(code, msg);
        return new Result<>(codeMsg);
    }

    /**
     * 执行失败返回自定义错误
     *
     * @param mg
     * @return
     */
    public static Result fail(CodeMsg mg) {
        return new Result<>(mg);
    }

//    /**
//     * 返回分页对象，分页信息存放在Response Header
//     * @param response
//     * @param pagingData
//     * @return
//     */
//    public static Result setPageResult(HttpServletResponse response, PagingData pagingData) {
//        Pagination pagination = Pagination.builder()
//                .current(pagingData.getCurrent())
//                .pages(pagingData.getPages())
//                .size(pagingData.getSize())
//                .total(pagingData.getTotal())
//                .build();
//
//        response.setCharacterEncoding("UTF-8");
//        response.setContentType("text/json;charset=utf-8");
//        response.setHeader("Access-Control-Expose-Headers", "X-Pagination");
//        response.setHeader("X-Pagination", JSONUtil.toJsonStr(pagination));
//
//        return Result.success(pagingData.getList());
//    }
}
